/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __DataStream_H__
#define __DataStream_H__

//#include "Prerequisites_kernel.h"
#include <istream>
//#include "OgreHeaderPrefix.h"


#include "kernel/string_def.h"
#include "kernel/threading/OgreThreadHeaders.h"
#include "kernel/observer_ptr.h"

namespace FD
{
	namespace Kernel
	{
		//typedef _StringBase String;

		/** Template version of cache based on static array.
		'cacheSize' defines size of cache in bytes. */
		template <size_t cacheSize>
		class StaticCache
		{
		protected:
			/// Static buffer
			char mBuffer[cacheSize];

			/// Number of bytes valid in cache (written from the beginning of static buffer)
			size_t mValidBytes;
			/// Current read position
			size_t mPos;

		public:
			/// Constructor
			StaticCache()
			{
				mValidBytes = 0;
				mPos = 0;
				memset(mBuffer, 0, cacheSize);
			}

			/** Cache data pointed by 'buf'. If 'count' is greater than cache size, we cache only last bytes.
			Returns number of bytes written to cache. */
			size_t cacheData(const void* buf, size_t count)
			{
				assert(avail() == 0 && "It is assumed that you cache data only after you have read everything.");

				if (count < cacheSize)
				{
					// number of bytes written is less than total size of cache
					if (count + mValidBytes <= cacheSize)
					{
						// just append
						memcpy(mBuffer + mValidBytes, buf, count);
						mValidBytes += count;
					}
					else
					{
						size_t begOff = count - (cacheSize - mValidBytes);
						// override old cache content in the beginning
						memmove(mBuffer, mBuffer + begOff, mValidBytes - begOff);
						// append new data
						memcpy(mBuffer + cacheSize - count, buf, count);
						mValidBytes = cacheSize;
					}
					mPos = mValidBytes;
					return count;
				}
				else
				{
					// discard all
					memcpy(mBuffer, (const char*)buf + count - cacheSize, cacheSize);
					mValidBytes = mPos = cacheSize;
					return cacheSize;
				}
			}
			/** Read data from cache to 'buf' (maximum 'count' bytes). Returns number of bytes read from cache. */
			size_t read(void* buf, size_t count)
			{
				size_t rb = avail();
				rb = (rb < count) ? rb : count;
				memcpy(buf, mBuffer + mPos, rb);
				mPos += rb;
				return rb;
			}

			/** Step back in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */
			bool rewind(size_t count)
			{
				if (mPos < count)
				{
					clear();
					return false;
				}
				else
				{
					mPos -= count;
					return true;
				}
			}
			/** Step forward in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */
			bool ff(size_t count)
			{
				if (avail() < count)
				{
					clear();
					return false;
				}
				else
				{
					mPos += count;
					return true;
				}
			}

			/** Returns number of bytes available for reading in cache after rewinding. */
			size_t avail() const
			{
				return mValidBytes - mPos;
			}

			/** Clear the cache */
			void clear()
			{
				mValidBytes = 0;
				mPos = 0;
			}
		};
		class FD_Kernel_Export DataStream : public FD::Kernel::CReferenced PUBLIC_GENERALALLOC
		{
		public:
			/// Streaming operators
			template<typename T> FD::Kernel::DataStream &operator>>(T &val);			///δ���κζ������,�����ֲ��public��
		public:
			enum AccessMode
			{
				READ = 1,
				WRITE = 2
			};

		protected:
			//// The name (e.g. resource name) that can be used to identify the source fot his data (optional)
			String mName;
			//// Size of the data in the stream (may be 0 if size cannot be determined)
			size_t mSize;
			//// What type of access is allowed (AccessMode)
			UINT16 mAccess;
#define OGRE_STREAM_TEMP_SIZE 128
		public:
			//// Constructor for creating unnamed streams
			DataStream(UINT16 accessMode) : mSize(0), mAccess(accessMode) {}
			DataStream() : mSize(0), mAccess(READ) {}
			//// Constructor for creating named streams
			DataStream(const String &name, UINT16 accessMode)
				: mName(name), mSize(0), mAccess(accessMode) {}
			DataStream(const String &name)
				: mName(name), mSize(0), mAccess(READ) {}

			//// Returns the name of the stream, if it has one.
			const String &getName()
			{
				return mName;
			}
			void setName(const String& name);

			//// Gets the access mode of the stream
			UINT16 getAccessMode() const
			{
				return mAccess;
			}
			/** Reports whether this stream is readable. */
			virtual bool isReadable() const
			{
				return (mAccess & READ) != 0;
			}
			/** Reports whether this stream is writeable. */
			virtual bool isWriteable() const
			{
				return (mAccess & WRITE) != 0;
			}
			virtual ~DataStream() {}

			/** Read the requisite number of bytes from the stream,
			stopping at the end of the file.
			@param buf Reference to a buffer pointer
			@param count Number of bytes to read
			@returns The number of bytes read
			*/
			virtual size_t read(void *buf, size_t count);
			/** Write the requisite number of bytes from the stream (only applicable to
			streams that are not read-only)
			@param buf Pointer to a buffer containing the bytes to write
			@param count Number of bytes to write
			@returns The number of bytes written
			*/
			virtual size_t write(const void *buf, size_t count);
			/** Get a single line from the stream.
			@remarks
			The delimiter character is not included in the data
			returned, and it is skipped over so the next read will occur
			after it. The buffer contents will include a
			terminating character.
			@note
			If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
			otherwise, it'll produce unexpected results.
			@param buf Reference to a buffer pointer
			@param maxCount The maximum length of data to be read, excluding the terminating character
			@param delim The delimiter to stop at
			@returns The number of bytes read, excluding the terminating character
			*/
			virtual size_t readLine(CHAR *buf, size_t maxCount, const String& delim = "\n" );
			/** Returns a String containing the next line of data, optionally
			trimmed for whitespace.
			@remarks
			This is a convenience method for text streams only, allowing you to
			retrieve a String object containing the next line of data. The data
			is read up to the next newline character and the result trimmed if
			required.
			@note
			If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
			otherwise, it'll produce unexpected results.
			@param
			trimAfter If true, the line is trimmed for whitespace (as in
			String.trim(true,true))
			*/
			virtual String getLine( bool trimAfter = true);
			/** Returns a String containing the entire stream.
			@remarks
			This is a convenience method for text streams only, allowing you to
			retrieve a String object containing all the data in the stream.
			*/
			virtual String getAsString();
			/** Skip a single line from the stream.
			@note
			If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
			otherwise, it'll produce unexpected results.
			@param delim The delimiter(s) to stop at
			@returns The number of bytes skipped
			*/
			virtual size_t skipLine(const String &delim);
			/** Skip a defined number of bytes. This can also be a negative value, in which case
			the file pointer rewinds a defined number of bytes. */
			virtual void skip(long count) = 0;
			/** Repositions the read point to a specified byte.
			*/
			virtual void seek( size_t pos ) = 0;
			/** Returns the current byte offset from beginning */
			virtual size_t tell() const = 0;
			/** Returns true if the stream has reached the end.
			*/
			virtual bool eof() const = 0;
			/** Returns the total size of the data to be read from the stream,
			or 0 if this is indeterminate for this stream.
			*/
			size_t size() const { return mSize; }
			/** Close the stream; this makes further operations invalid. */
			virtual void close() = 0;
		};

		class MemoryDataStream;

		class FD_Kernel_Export CDataStreamReader : public FD::Kernel::CReferenced
		{
		public:
			/// <summary>
			///��ȡһ���ַ������󣬻��Զ��ڰ��ַ�������Ϊ0�ж�	
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 readGBKString(FD::Kernel::FdGbkString& value);

			/// <summary>
			///��ȡһ���ַ������󣬰��ַ������볤������ȡ
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 readGBKString(FD::Kernel::FdGbkString& value, INT32 length);
		public:
			enum DataStreamOrder
			{
				BIG_ENDIAN_ORDER    = 1,  /// big-endian (network) order            		
				LITTLE_ENDIAN_ORDER = 2,  /// little-endian order
			};

			CDataStreamReader(DataStream& dataStream);
			CDataStreamReader(DataStream& dataStream, DataStreamOrder dataStreamOrder);
			virtual ~CDataStreamReader();
			INT32 readBool(bool& value);
			INT32 readChar(CHAR& value);
			INT32 readUChar(UCHAR& value);
			INT32 readWChar(WCHAR& value);
			INT32 readByte(BYTE& value);
			INT32 readInt8(INT8& value);
			INT32 readUInt8(UINT8& value);
			INT32 readInt16(INT16& value);
			INT32 readUInt16(UINT16& value);
			INT32 readInt32(INT32& value);
			INT32 readUInt32(UINT32& value);
			INT32 readInt64(INT64& value);
			INT32 readUInt64(UINT64& value);
			INT32 readReal32(float& value);
			INT32 readReal64(double& value);

			/// <summary>
			/// 
			/// </summary>
			/// <param name=""></param>
			/// <returns></returns>
			INT32 readObjectAddr(void*& value);
			//INT32 readSizeT(size_t& value);   //
			/// <summary>
			///��ȡһ���ַ������󣬻��Զ��ڰ��ַ�������Ϊ0�ж�	
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 readString(String& value);	//
			/// <summary>
			///��ȡһ���ַ������󣬰��ַ������볤������ȡ
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 readString(String& value, INT32 length);	//
			INT32 readRaw(MemoryDataStream& value, INT32 length);

			bool eof();
			DataStream& dataStream();
		protected:
		private:
			DataStream& mDataStream;
			bool mFlipBytes;
		};

		class FD_Kernel_Export CDataStreamWriter : public FD::Kernel::CReferenced
		{
		public:
			/// <summary>
			/// д��һ���ַ������󣬻��Զ��ں����0		
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 writeGBKString(const FD::Kernel::FdGbkString& value);
			/// <summary>
			/// д��һ���ַ������󣬲����Զ��ں����0		
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 writeGBKString(const FD::Kernel::FdGbkString& value, INT32 length);
		public:
			enum DataStreamOrder
			{
				BIG_ENDIAN_ORDER    = 1,  /// big-endian (network) order            		
				LITTLE_ENDIAN_ORDER = 2,  /// little-endian order
			};
			CDataStreamWriter(DataStream& dataStream);
			CDataStreamWriter(DataStream& dataStream, DataStreamOrder dataStreamOrder);
			virtual ~CDataStreamWriter();
			INT32 writeBool(bool value);
			INT32 writeChar(CHAR value);
			INT32 writeUChar(UCHAR value);
			INT32 writeWChar(WCHAR value);
			INT32 writeByte(BYTE value);
			INT32 writeInt8(INT8 value);
			INT32 writeUInt8(UINT8 value);
			INT32 writeInt16(INT16 value);
			INT32 writeUInt16(UINT16 value);
			INT32 writeInt32(INT32 value);
			INT32 writeUInt32(UINT32 value);
			INT32 writeInt64(INT64 value);
			INT32 writeUInt64(UINT64 value);
			INT32 writeReal32(float value);
			INT32 writeReal64(double value);

			/// <summary>
			/// д��һ�������ַ��
			/// ���ô˺����󣬽����³־û��Ķ�������������32λ��64λϵͳ��ͨ�ã�
			/// </summary>
			/// <param name="value">�����ַ</param>
			/// <returns></returns>
			INT32 writeObjectAddr(void* value);
			//INT32 writeSizeT(size_t value);   //

			/// <summary>
			/// д��һ���ַ������󣬻��Զ��ں����0		
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 writeString(const String& value);	//

			/// <summary>
			/// д��һ���ַ������󣬲����Զ��ں����0		
			/// </summary>
			/// <param name="value">�ַ�������</param>
			/// <returns></returns>
			INT32 writeString(const String& value, INT32 length);	//
			INT32 writeRaw(MemoryDataStream& value);

			bool eof();
			DataStream& dataStream();
		protected:
		private:
			DataStream& mDataStream;
			bool mFlipBytes;
		};

		/** Shared pointer to allow data streams to be passed around without
		worrying about deallocation
		*/
		/*typedef FD::Kernel::ref_ptr<FD::Kernel::DataStream> FD::Kernel::DataStreamPtr;*/
		class FD_Kernel_Export DataStreamPtr : public FD::Kernel::ref_ptr<FD::Kernel::DataStream>
		{
		public:
			DataStreamPtr() : FD::Kernel::ref_ptr<FD::Kernel::DataStream>() {}
			explicit DataStreamPtr(FD::Kernel::DataStream *rep) : FD::Kernel::ref_ptr<FD::Kernel::DataStream>(rep) {}
			DataStreamPtr(const DataStreamPtr &r) : FD::Kernel::ref_ptr<FD::Kernel::DataStream>(r) {}

			FD::Kernel::DataStream *get() const
			{
				return FD::Kernel::ref_ptr<FD::Kernel::DataStream>::get();
			}
		};
		//// List of FD::Kernel::DataStream items
		/*typedef list<FD::Kernel::DataStreamPtr> FD::Kernel::DataStreamList;*/
		class FD_Kernel_Export DataStreamList : public FD::Kernel::CReferenced
		{
		public:
			typedef std::list<FD::Kernel::DataStreamPtr> InternalList;
			typedef InternalList::iterator iterator;
			typedef InternalList::const_iterator const_iterator;
			typedef InternalList::reverse_iterator reverse_iterator;
			typedef InternalList::const_reverse_iterator const_reverse_iterator;
			typedef InternalList::reference reference;
			typedef InternalList::const_reference const_reference;
			typedef InternalList::value_type value_type;
			RESERVE_CONTAINER_FUNCTION(mList); 			///����������ĺ���(��������ͺͷ���ֵ�޹صĺ�������begin/end)
			iterator insert(iterator pos, FD::Kernel::DataStreamPtr const &t)
			{
				return mList.insert(pos, t);
			}

		private:
			InternalList mList;

		public:
			DataStreamList() {}
			void push_back(FD::Kernel::DataStreamPtr const &t)
			{
				mList.push_back(t);
			}
			void push_front(FD::Kernel::DataStreamPtr const   &t)
			{
				mList.push_front(t);
			}
			void pop_back()
			{
				mList.pop_back();
			}

			void pop_front()
			{
				mList.pop_front();
			}

			FD::Kernel::DataStreamPtr &front()
			{
				return mList.front();
			}
			FD::Kernel::DataStreamPtr &back()
			{
				return mList.back();
			}
			FD::Kernel::DataStreamPtr &at(UINT32 pos)
			{
				iterator it = begin();
				for(UINT32 i = 0; i < pos; i++)
					it++;
				return *it;
			}
			void insert(UINT32 pos, FD::Kernel::DataStreamPtr const &t)
			{
				iterator it = begin();
				for(UINT32 i = 0; i < pos; i++)
					it++;
				mList.insert(it, t);
			}
			void remove(size_t pos)
			{
				iterator it = begin();
				for(UINT32 i = 0; i < pos; i++)
					it++;
				mList.erase(it);
			}
			bool empty() const
			{
				return mList.empty();
			}

			size_t size() const
			{
				return mList.size();
			}
			void resize(size_t newSize)
			{
				mList.resize(newSize);
			}
			void clear()
			{
				mList.clear();
			}
		};
		
		//// Shared pointer to list of FD::Kernel::DataStream items
		/*typedef FD::Kernel::ref_ptr<FD::Kernel::DataStreamList> FD::Kernel::DataStreamListPtr;*/
		class FD_Kernel_Export DataStreamListPtr : public FD::Kernel::ref_ptr<FD::Kernel::DataStreamList>
		{
		public:
			DataStreamListPtr() : FD::Kernel::ref_ptr<DataStreamList>() {}
			explicit DataStreamListPtr(DataStreamList *rep) : FD::Kernel::ref_ptr<DataStreamList>(rep) {}
			DataStreamListPtr(const DataStreamListPtr &r) : FD::Kernel::ref_ptr<DataStreamList>(r) {}

			FD::Kernel::DataStreamList *get() const
			{
				return FD::Kernel::ref_ptr<FD::Kernel::DataStreamList>::get();
			}
		};
		/** Common subclass of DataStream for handling data from chunks of memory.
		*/
		class FD_Kernel_Export MemoryDataStream : public FD::Kernel::DataStream
		{
		protected:
			//// Pointer to the start of the data area
			UCHAR *mData;
			//// Pointer to the current position in the memory
			UCHAR *mPos;
			//// Pointer to the end of the memory
			UCHAR *mEnd;
			//// Do we delete the memory on close
			bool mFreeOnClose;

		public:
			MemoryDataStream(){};

			/** Wrap an existing memory chunk in a stream.
			@param pMem Pointer to the existing memory
			@param size The size of the memory chunk in bytes
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed. Note: it's important that if you set
			with a category of MEMCATEGORY_GENERAL ensure the freeing of memory
			matches up.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(void* pMem, size_t size, bool freeOnClose = false, bool readOnly = false);
			/** Wrap an existing memory chunk in a named stream.
			@param name The name to give the stream
			@param pMem Pointer to the existing memory
			@param size The size of the memory chunk in bytes
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed. Note: it's important that if you set
			with a category of MEMCATEGORY_GENERAL ensure the freeing of memory
			matches up.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(const String& name, void* pMem, size_t size, 
				bool freeOnClose = false, bool readOnly = false);
			/** Create a stream which pre-buffers the contents of another stream.
			@remarks
			This constructor can be used to intentionally read in the entire
			contents of another stream, copying them to the internal buffer
			and thus making them available in memory as a single unit.
			@param sourceStream Another FD::Kernel::DataStream which will provide the source
			of data
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(DataStream& sourceStream, 
				bool freeOnClose = true, bool readOnly = false);

			/** Create a stream which pre-buffers the contents of another stream.
			@remarks
			This constructor can be used to intentionally read in the entire
			contents of another stream, copying them to the internal buffer
			and thus making them available in memory as a single unit.
			@param sourceStream Weak reference to another FD::Kernel::DataStream which will provide the source
			of data
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(DataStreamPtr& sourceStream, 
				bool freeOnClose = true, bool readOnly = false);

			/** Create a named stream which pre-buffers the contents of
			another stream.
			@remarks
			This constructor can be used to intentionally read in the entire
			contents of another stream, copying them to the internal buffer
			and thus making them available in memory as a single unit.
			@param name The name to give the stream
			@param sourceStream Another FD::Kernel::DataStream which will provide the source
			of data
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(const String& name, DataStream& sourceStream, 
				bool freeOnClose = true, bool readOnly = false);

			/** Create a named stream which pre-buffers the contents of
			another stream.
			@remarks
			This constructor can be used to intentionally read in the entire
			contents of another stream, copying them to the internal buffer
			and thus making them available in memory as a single unit.
			@param name The name to give the stream
			@param sourceStream Another FD::Kernel::DataStream which will provide the source
			of data
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(const String& name, const DataStreamPtr& sourceStream, 
				bool freeOnClose = true, bool readOnly = false);

			/** Create a stream with a brand new empty memory chunk.
			@param size The size of the memory chunk to create in bytes
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(size_t size, bool freeOnClose = true, bool readOnly = false);
			/** Create a named stream with a brand new empty memory chunk.
			@param name The name to give the stream
			@param size The size of the memory chunk to create in bytes
			@param freeOnClose If true, the memory associated will be destroyed
			when the stream is destroyed.
			@param readOnly Whether to make the stream on this memory read-only once created
			*/
			MemoryDataStream(const String& name, size_t size, bool freeOnClose = true, bool readOnly = false);
			~MemoryDataStream();

			/** Get a pointer to the start of the memory block this stream holds. */
			UCHAR *getPtr()
			{
				return mData;
			}

			/** Get a pointer to the current position in the memory block this stream holds. */
			UCHAR *getCurrentPtr()
			{
				return mPos;
			}

			/** @copydoc DataStream::read
			*/
			size_t read(void *buf, size_t count);
			/** @copydoc DataStream::write
			*/
			size_t write(const void *buf, size_t count);
			/** @copydoc DataStream::readLine
			*/
			size_t readLine(CHAR *buf, size_t maxCount, const String& delim = "\n");
			/** @copydoc DataStream::skipLine
			*/
			size_t skipLine(const String& delim = "\n");
			/** @copydoc DataStream::skip
			*/
			void skip(long count);
			/** @copydoc DataStream::seek
			*/
			void seek( size_t pos );
			/** @copydoc DataStream::tell
			*/
			size_t tell() const;
			/** @copydoc DataStream::eof
			*/
			bool eof() const;
			/** @copydoc DataStream::close
			*/
			void close();
			/** Sets whether or not to free the encapsulated memory on close. */
			void setFreeOnClose(bool free)
			{
				mFreeOnClose = free;
			}
		};
		/** Shared pointer to allow memory data streams to be passed around without
		worrying about deallocation
		*/
		/*typedef FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream> FD::Kernel::MemoryDataStreamPtr;*/
		class FD_Kernel_Export MemoryDataStreamPtr : public FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream>
		{
		public:
			MemoryDataStreamPtr() : FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream>() {}
			/*MemoryDataStreamPtr(void * pMen) :  FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream>((FD::Kernel::MemoryDataStream *)pMen) {}*/
			explicit MemoryDataStreamPtr(FD::Kernel::MemoryDataStream *rep) : FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream>(rep) {}
			MemoryDataStreamPtr(const MemoryDataStreamPtr &r) : FD::Kernel::ref_ptr<FD::Kernel::MemoryDataStream>(r) {}
			explicit MemoryDataStreamPtr(DataStreamPtr& ptr)
			{
				if(!ptr.isNull())
				{
					FD::Kernel::DataStream* ds = ptr.getPointer();
					FD::Kernel::MemoryDataStream* mds = reinterpret_cast<FD::Kernel::MemoryDataStream*>(ds);
					if(mds == NULL && ds != NULL)
					{
						FD::Kernel::MemoryDataStream* stream = OGRE_NEW FD::Kernel::MemoryDataStream(*ds);
						this->bind(stream);
					}
					else if(mds != NULL)
					{
						this->bind(mds);
					}
				}
			}

			operator DataStreamPtr()const
			{
				DataStreamPtr ptr;
				ptr.bind(_ptr);
				return ptr;
			}
		};
		/** Common subclass of DataStream for handling data from
		std::basic_istream.
		*/
		class FD_Kernel_Export FileStreamDataStream : public FD::Kernel::DataStream
		{
		protected:
			//// Reference to source stream (read)
			std::istream *mpInStream;
			//// Reference to source file stream (read-only)
			std::ifstream *mpFStreamRO;
			//// Reference to source file stream (read-write)
			std::fstream *mpFStream;
			bool mFreeOnClose;

			void determineAccess();
		public:
			/** Construct a read-only stream from an STL stream
			@param s Pointer to source stream
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class
			*/
			FileStreamDataStream(std::ifstream* s, 
				bool freeOnClose = true);
			/** Construct a read-write stream from an STL stream
			@param s Pointer to source stream
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class
			*/
			FileStreamDataStream(std::fstream* s, 
				bool freeOnClose = true);
			/** Construct named read-only stream from an STL stream
			@param name The name to give this stream
			@param s Pointer to source stream
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class
			*/
			FileStreamDataStream(const String& name, 
				std::ifstream* s, 
				bool freeOnClose = true);
			/** Construct named read-write stream from an STL stream
			@param name The name to give this stream
			@param s Pointer to source stream
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class
			*/
			FileStreamDataStream(const String& name, 
				std::fstream* s, 
				bool freeOnClose = true);
			/** Construct named read-only stream from an STL stream, and tell it the size
			@remarks
			This variant tells the class the size of the stream too, which
			means this class does not need to seek to the end of the stream
			to determine the size up-front. This can be beneficial if you have
			metadata about the contents of the stream already.
			@param name The name to give this stream
			@param s Pointer to source stream
			@param size Size of the stream contents in bytes
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class. If you specify 'true' for this you
			MEMCATEGRORY_GENERAL.
			*/
			FileStreamDataStream(const String& name, 
				std::ifstream* s, 
				size_t size, 
				bool freeOnClose = true);
			/** Construct named read-write stream from an STL stream, and tell it the size
			@remarks
			This variant tells the class the size of the stream too, which
			means this class does not need to seek to the end of the stream
			to determine the size up-front. This can be beneficial if you have
			metadata about the contents of the stream already.
			@param name The name to give this stream
			@param s Pointer to source stream
			@param size Size of the stream contents in bytes
			@param freeOnClose Whether to delete the underlying stream on
			destruction of this class. If you specify 'true' for this you
			MEMCATEGRORY_GENERAL.
			*/
			FileStreamDataStream(const String& name, 
				std::fstream* s, 
				size_t size, 
				bool freeOnClose = true);

			FileStreamDataStream(){};

		public:
			~FileStreamDataStream();
			/** @copydoc DataStream::read
			*/
			size_t read(void *buf, size_t count);
			/** @copydoc DataStream::write
			*/
			size_t write(const void *buf, size_t count);
			/** @copydoc DataStream::readLine
			*/
			size_t readLine(CHAR *buf, size_t maxCount, const String& delim = "\n");
			/** @copydoc DataStream::skip
			*/
			void skip(long count);
			/** @copydoc DataStream::seek
			*/
			void seek( size_t pos );
			/** @copydoc DataStream::tell
			*/
			size_t tell() const;
			/** @copydoc DataStream::eof
			*/
			bool eof() const;
			/** @copydoc DataStream::close
			*/
			void close();
		};
		/** Common subclass of DataStream for handling data from C-style file
		handles.
		@remarks
		Use of this class is generally discouraged; if you want to wrap file
		FileStreamDataStream. However, since there are quite a few applications
		and libraries still wedded to the old FILE handle access, this stream
		wrapper provides some backwards compatibility.
		*/

		/*	for variant length.	made by zhangchaochao*/
		class FD_Kernel_Export BufferDataStream : public FD::Kernel::DataStream
		{
		protected:
			std::stringbuf mBuf;
			std::iostream* mpStream;
			size_t mCurOffset;

		public:
			BufferDataStream(FD::Kernel::DataStream& stream);

			BufferDataStream(const CHAR* stream,UINT32 size);

			BufferDataStream();
			BufferDataStream(const String& name);

			virtual ~BufferDataStream();

			virtual size_t read(void *buf, size_t count);

			virtual size_t write(const void *buf, size_t count);

			virtual size_t readLine(CHAR *buf, size_t maxCount, const String &delim = "\n" );

			virtual String getLine( bool trimAfter = true);

			virtual String getAsString();

			virtual size_t skipLine(const String& delim = "\n");

			virtual void skip(long count);

			virtual void seek( size_t pos );

			virtual size_t tell() const;

			virtual bool eof() const;

			virtual void close();
		};

		class FD_Kernel_Export FileHandleDataStream : public FD::Kernel::DataStream
		{
		protected:
			FILE *mFileHandle;
		public:
			//// Create stream from a C file handle
			FileHandleDataStream(FILE *handle, UINT16 accessMode );
			FileHandleDataStream(FILE *handle);
			//// Create named stream from a C file handle
			FileHandleDataStream(const String &name, FILE *handle, UINT16 accessMode);
			FileHandleDataStream(const String &name, FILE *handle);

			FileHandleDataStream(){};

		public:
			//// Create stream from a binary file(exist or not)
			FileHandleDataStream(const String &strFullPath, UINT16 accessMode);
		public:
			~FileHandleDataStream();
			/** @copydoc DataStream::read
			*/
			size_t read(void *buf, size_t count);
			/** @copydoc DataStream::write
			*/
			size_t write(const void *buf, size_t count);
			/** @copydoc DataStream::skip
			*/
			void skip(long count);

			/** @copydoc DataStream::seek
			*/
			void seek( size_t pos );
			/** @copydoc DataStream::tell
			*/
			size_t tell() const;
			/** @copydoc DataStream::eof
			*/
			bool eof() const;
			/** @copydoc DataStream::close
			*/
			void close();
		};

		class FD_Kernel_Export CSqlBlobStream :
			public FD::Kernel::DataStream
		{
		public:
			/// <summary>
			/// Ĭ����������
			/// </summary>
			~CSqlBlobStream();
		public:
			/// <summary>
			/// ��ȡָ���������ݵ�ָ�������У���ȡ��ɣ��α�����Count��λ�á�
			/// </summary>
			/// <param name="buf">�����ַ</param>
			/// <param name="count">��ȡ���ݴ�С</param>
			/// <returns>ʵ�ʶ�ȡ���ݳ���</returns>
			virtual size_t read(void *buf, size_t count);
			/// <summary>
			/// ����ָ�����ȵ����ݡ�
			/// </summary>
			/// <param name="count">�������ݳ���</param>
			/// <returns></returns>
			virtual void skip(long count);
			/// <summary>
			/// �α�λ���ƶ���ָ��λ����
			/// </summary>
			/// <param name="pos">ָ��λ��</param>
			/// <returns></returns>
			virtual void seek( size_t pos );
			/// <summary>
			/// ��ȡ�α�λ��
			/// </summary>
			/// <param name=""></param>
			/// <returns>�α�λ��</returns>
			virtual size_t tell() const;
			/// <summary>
			/// �ж϶�ȡ�Ƿ����
			/// </summary>
			/// <param name=""></param>
			/// <returns>��ȡ����������true;���򣬷���false</returns>
			virtual bool eof() const;
			/// <summary>
			/// �ر���
			/// </summary>
			/// <param name=""></param>
			/// <returns></returns>
			virtual void close();
			/// <summary>
			/// ת��Ϊ�ڴ���
			/// </summary>
			/// <param name=""></param>
			/// <returns>�ڴ�������
			/// SqlServer ���ݿ�Blob������ֻ�е�pos ��= 0��ʱ�򣬷��ؿա�</returns>
			virtual FD::Kernel::MemoryDataStreamPtr toDataStream();

			/*---------��֧�ַ���-----------------*/

			/// <summary>
			/// ��ָ��������д��ָ�����ȵ����ݡ���֧�ִ˷�����������Ч��
			/// </summary>
			/// <param name="buf">�����ַ</param>
			/// <param name="count">��ȡ���ݴ�С</param>
			/// <returns>ʵ�ʶ�ȡ���ݳ���</returns>
			virtual size_t write(const void *buf, size_t count);

			virtual size_t readLine(CHAR *buf, size_t maxCount, const String &delim = "\n" );

			virtual String getLine( bool trimAfter = true);

			virtual String getAsString();

			virtual size_t skipLine(const String& delim = "\n");
		public:
			/// <summary>
			/// ��ȡ��������
			/// </summary>
			/// <param name=""></param>
			/// <returns>��������</returns>
			virtual String DriverName() const;
			/// <summary>
			/// ��ȡԭʼ����
			/// </summary>
			/// <param name=""></param>
			/// <returns>�����׵�ַ</returns>
			virtual const CHAR* data() const;
		protected:
			/// <summary>
			/// Ĭ�Ϲ��캯��
			/// </summary>
			explicit CSqlBlobStream();
		};
	}
}

#include "kernel/OgreHeaderSuffix.h"

#endif

